package db;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * A data access object (DAO) providing persistence and search support for Place
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see db.Place
 * @author MyEclipse Persistence Tools
 */

public class PlaceDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(PlaceDAO.class);
	// property constants
	public static final String NAME = "name";

	protected void initDao() {
		// do nothing
	}

	public void save(Place transientInstance) {
		log.debug("saving Place instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Place persistentInstance) {
		log.debug("deleting Place instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Place findById(java.lang.Integer id) {
		log.debug("getting Place instance with id: " + id);
		try {
			Place instance = (Place) getHibernateTemplate().get("db.Place", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Place instance) {
		log.debug("finding Place instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Place instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Place as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}

	public List findAll() {
		log.debug("finding all Place instances");
		try {
			String queryString = "from Place";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Place merge(Place detachedInstance) {
		log.debug("merging Place instance");
		try {
			Place result = (Place) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Place instance) {
		log.debug("attaching dirty Place instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Place instance) {
		log.debug("attaching clean Place instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static PlaceDAO getFromApplicationContext(ApplicationContext ctx) {
		return (PlaceDAO) ctx.getBean("PlaceDAO");
	}
	

	
	public Map getPlace(int pageNo, int pageSize, String[][] order, Object[][] where, String[][] fields, String[] join) {
		ProjectionList pl = Projections.projectionList();	
		for (int i = 0; i < fields.length; i++) {
			String[] field = fields[i];
			if("group".equals(field[0])){
				pl.add(Projections.groupProperty(field[1]));
			}else{
				pl.add(Projections.property(field[1]));
			}
		}
		
		DetachedCriteria dc = DetachedCriteria.forClass(Place.class);
		if(join != null && join.length > 0)
		for(int i=0;i<join.length;i++){
			if("title".equals(join[i]))
			dc.createAlias("title", "t");
			else if("group".equals(join[i]))
			dc.createAlias("group","g");
		}
		dc.setProjection(pl);

		if(order != null && order.length > 0)
		for(int i=0; i<order.length; i++){
			String[] temp = order[i];
			if ("desc".equals(order[i][0])) {
				dc.addOrder(Order.desc(order[i][1]));
			} else if ("asc".equals(order[i][1])) {
				dc.addOrder(Order.asc(order[i][1]));
			}
		}
		
		if(where != null && where.length > 0)
		for(int i=0; i<where.length; i++){
			String condition = String.valueOf(where[i][0]);
			String filed = String.valueOf(where[i][1]);
			if("eq".equals(condition)){
				dc.add(Property.forName(filed).eq(where[i][2]));
			}else if("like".equals(condition)){
				dc.add(Property.forName(filed).like("%" + where[i][2] + "%"));
			}else if("ne".equals(condition)){
				dc.add(Property.forName(filed).ne(where[i][2]));
			}else if("or".equals(condition)){
				dc.add(handleOr((List)where[i][2]));
			}
		}
       
		int recordSize = getCount(where);
		
		List data = getHibernateTemplate().findByCriteria(dc,pageNo * pageSize, pageSize);
		
		int pageTotal = pageSize == 0 ? 1 : recordSize % pageSize == 0 ? recordSize / pageSize : recordSize / pageSize + 1;
		Map map = new HashMap();
		map.put("data", data);
		map.put("recordSize", recordSize);
		map.put("pageTotal", pageTotal);
		map.put("pageSize", pageSize);
		map.put("pageNo", pageNo);
		return map;
	}
	
	public int getCount(Object[][] where){
		DetachedCriteria dc = DetachedCriteria.forClass(Place.class)
		.setProjection(Projections.rowCount());
		
		if(where != null && where.length > 0)
		for(int i=0;i<where.length;i++){
			String condition = String.valueOf(where[i][0]);
			String filed = String.valueOf(where[i][1]);
			if("eq".equals(condition)){
				dc.add(Property.forName(filed).eq(where[i][2]));
			}else if("like".equals(condition)){
				dc.add(Property.forName(filed).like("%" + where[i][2] + "%"));
			}else if("ne".equals(condition)){
				dc.add(Property.forName(filed).ne(where[i][2]));
			}else if("or".equals(condition)){
				dc.add(handleOr((List)where[i][2]));
			}
		}
		
		return (Integer) getHibernateTemplate().findByCriteria(dc).get(0);
	}
	
	public LogicalExpression handleOr(List list){
		LogicalExpression le = null;
		SimpleExpression se = null;
		SimpleExpression se1 = null;
		SimpleExpression se2 = null;
		
		for(int i= list.size() - 1;i >= 0;i--){
			Object[] where = (Object[])list.get(i);
			String condition = String.valueOf(where[0]);
			String filed = String.valueOf(where[1]);
			
			if("eq".equals(condition)){
				if(le == null){
					if(se1 == null)
						se1 = Restrictions.eq(filed, where[2]);
					else if(se2 == null)
						se2 = Restrictions.eq(filed, where[2]);
				}else{
					se = Restrictions.eq(filed, where[2]);
				}
			}else if("like".equals(condition)){
				if(le == null){
					if(se1 == null)
						se1 = Restrictions.like(filed, "%" + where[2] + "%");
					else if(se2 == null)
						se2 = Restrictions.like(filed, "%" + where[2] + "%");
				}else{
					se = Restrictions.like(filed, "%" + where[2] + "%");
				}
			}else if("ne".equals(condition)){
				if(le == null){
					if(se1 == null)
						se1 = Restrictions.ne(filed, where[2]);
					else if(se2 == null)
						se2 = Restrictions.ne(filed, where[2]);
				}else{
					se = Restrictions.ne(filed, where[2]);
				}
			}
			
			if(le == null){
				if(se1 != null && se2 != null){
					le = Restrictions.or(se1,se2);
				}
			}else{
				le = Restrictions.or(se,le);
			}
		}
		
		return le;
	}
}